package com.hippy.lib.utils

import android.content.Context
import android.content.SharedPreferences

class SPUtils {
    private var sp: SharedPreferences

    private constructor(spName: String, mode: Int = Context.MODE_PRIVATE) {
        sp = Utils.context.getSharedPreferences(spName, mode)
    }

    companion object {
        private val SP_UTILS_MAP = mutableMapOf<String, SPUtils?>()
        private const val DEFAULT_SP_NAME = "spUtils"

        fun getInstance(spName: String? = null, mode: Int = Context.MODE_PRIVATE): SPUtils {
            var spNameReal = spName
            if (StringUtils.isSpace(spName)) {
                spNameReal = DEFAULT_SP_NAME
            }
            var spUtils = SP_UTILS_MAP[spNameReal]
            if (spUtils == null) {
                synchronized(SPUtils::class.java) {
                    spUtils = SP_UTILS_MAP[spNameReal]
                    if (spUtils == null) {
                        spUtils = SPUtils(spNameReal!!, mode)
                        SP_UTILS_MAP[spNameReal] = spUtils
                    }
                }
            }
            return spUtils!!
        }
    }

    fun put(key: String, value: String?, isCommit: Boolean = false) {
        if (isCommit) {
            sp.edit().putString(key, value ?: "").commit()
        } else {
            sp.edit().putString(key, value ?: "").apply()
        }
    }

    fun getString(key: String, defaultValue: String? = null): String? {
        return sp.getString(key, defaultValue)
    }

    fun put(key: String, value: Boolean, isCommit: Boolean = false) {
        if (isCommit) {
            sp.edit().putBoolean(key, value).commit()
        } else {
            sp.edit().putBoolean(key, value).apply()
        }
    }

    fun getBoolean(key: String, defaultValue: Boolean = false): Boolean {
        return sp.getBoolean(key, defaultValue)
    }

}